import React, { useState, useEffect } from "react";
import axios from "axios";
import './Newspage.css';
import Navbar from './components/Navbar';

function NewsPagination() {
  const [news, setNews] = useState([]);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(0);
  const [activeLabel, setActiveLabel] = useState("全部");

  // 你可以根据实际类别定死分类
  const labels = ["全部", "科技", "财经","游戏","军事","汽车","体育","房产","教育","其他"];

  // 获取分页新闻（可选标签）
  const fetchNews = async (page) => {
    try {
      const params = {
        page: page,
        limit: 10,
        label:activeLabel
      };


      const response = await axios.get("http://localhost:8080/newsLabel/page", {
        params,
        headers: {
          'Authorization': localStorage.getItem('token'),
          'Content-Type': 'application/json',
        },
      });

      setNews(response.data.data.content);
      // 后端可以返回 total 否则你可固定也行
      setTotalPages(Math.ceil(response.data.data.total / 10));
    } catch (error) {
      console.error("加载新闻失败", error);
    }
  };

  useEffect(() => {
    fetchNews(page);
  }, [page, activeLabel]);

  const handleLabelClick = (label) => {
    setActiveLabel(label);
    setPage(1); // 切换分类时重置页码
  };

  return (
    <div>
      <Navbar />
      {/* 分类标签区域 */}
      <div className="labels-container">
          {labels.map((label) => (
            <button
              key={label}
              onClick={() => handleLabelClick(label)}
              className={`label-btn ${activeLabel === label ? "active" : ""}`}
            >
              {label}
            </button>
          ))}
        </div>
      <div className="news-container">
        <h2 className="title">新闻列表</h2>

        

        {/* 新闻列表 */}
        <ul className="news-list">
          {news.map((item, index) => (
            <div className="news-item" key={index}>
              <li className="news-title">{item.title}</li>
              <p className="news-content">{item.content}</p>
            </div>
          ))}
        </ul>

        {/* 分页控件 */}
        <div className="pagination">
          <button
            onClick={() => setPage((prev) => Math.max(prev - 1, 1))}
            disabled={page === 1}
            className="pagination-btn"
          >
            上一页
          </button>
          <span className="page-info">第 {page} 页</span>
          <button
            onClick={() => setPage((prev) => Math.min(prev + 1, totalPages))}
            disabled={page === totalPages}
            className="pagination-btn"
          >
            下一页
          </button>
        </div>
      </div>
    </div>
  );
}

export default NewsPagination;